package com.legend.ddz.framework.impl;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * 
 * @author zhugh
 * @date 2012-7-27 下午8:36:23
 * @description TODO
 * 
 */

public class AndroidFastRenderView extends SurfaceView implements Runnable
{

	Bitmap framebuffer;
	AndroidGame game;
	SurfaceHolder holder;
	Thread renderThread = null;
	volatile boolean running = false;

	public AndroidFastRenderView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		SurfaceHolder localSurfaceHolder = getHolder();
		this.holder = localSurfaceHolder;
	}

	public void initView(AndroidGame paramAndroidGame, Bitmap paramBitmap)
	{
		this.game = paramAndroidGame;
		this.framebuffer = paramBitmap;
	}

	public void pause()
	{
		this.running = true;
		while (true)
			try
			{
				this.renderThread.join();
				return;
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
	}

	public void resume()
	{
		this.running = true;
		Thread localThread = new Thread(this);
		this.renderThread = localThread;
		this.renderThread.start();
	}

	@Override
	public void run()
	{
		Rect dstRect=new Rect();  
		long startTime = System.nanoTime();
		while (running)
		{
			if (!this.running){
				return;
			}
			if (!this.holder.getSurface().isValid()){
				continue; 
			}
			float deltaTime = (float) (System.nanoTime() - startTime) / 1000000000.0f;
			this.game.getCurrentScreen().update(deltaTime);
			this.game.getCurrentScreen().present(deltaTime);
			Canvas localCanvas = this.holder.lockCanvas();
			localCanvas.getClipBounds(dstRect);
			Bitmap localBitmap = this.framebuffer;
			localCanvas.drawBitmap(localBitmap, null, dstRect, null);
			this.holder.unlockCanvasAndPost(localCanvas);
		}
	}

}
